﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace LANmine
{
    public partial class CreateTeam : Form
    {
        private Language lmLang;
        private User lmUser;
        private Database roDb = new Database("ro");
        private Database rwDb = new Database("rw");

        /** Escape Handler */
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Escape) this.Close();
            return base.ProcessCmdKey(ref msg, keyData);
        }

        public CreateTeam(Language lmLang, User lmUser)
        {
            /** Save objects */
            this.lmLang = lmLang;
            this.lmUser = lmUser;

            InitializeComponent();
            ApplyLanguage();
        }

        #region Language Specifications
        /**
         * MainForm::ApplyLanguage()
         * ---------------------------
         * Overwrite all text properties of all elements in all forms with the right ones.
         */
        private void ApplyLanguage()
        {
            /** Window Title */
            this.Text = this.lmLang.GetString("compos.btnCreateTeam");

            /** Header */
            lblTeamName.Text = this.lmLang.GetString("cteam.lblTeamName");
            lblCreateTeam.Text = this.lmLang.GetString("compos.btnCreateTeam");

            /** Other controls */
            txtTeamTag.Text = this.lmLang.GetString("cteam.txtTeamTag");
            btnCreateTeam.Text = this.lmLang.GetString("compos.btnCreateTeam");
        }
        #endregion

        #region Member Functions
        /**
         * ComposForm::TeamTaken
         * Check if the given team name or tag is taken.
         */
        private bool TeamTaken(String tName, String tTag)
        {
            /** Build query string */
            SqlCommand cQry = new SqlCommand("lmCheckTeam");
            cQry.CommandType = CommandType.StoredProcedure;

            /** Get connection */
            SqlConnection dbConn = this.roDb.getDbConn();

            /** Set the connection for the query¨*/
            cQry.Connection = dbConn;

            /** Add and set parameters */
            cQry.Parameters.Add("@TeamName", SqlDbType.VarChar, 50);
            cQry.Parameters.Add("@TeamTag", SqlDbType.VarChar, 5);

            cQry.Parameters["@TeamName"].Value = tName.Trim();
            cQry.Parameters["@TeamTag"].Value = tTag.Trim();

            try
            {
                /** Open connection */
                dbConn.Open();

                Boolean hasRows = cQry.ExecuteReader().HasRows;

                /** Close connection */
                dbConn.Close();

                /** Check the database for results */
                return hasRows;

            }
            catch (Exception e)
            {
                MessageBox.Show(this.lmLang.GetString("cteam.errCheckTeam") + "\n" + e.Message);
                return false;
            }
        }

        /**
         * ComposForm::AddTeam
         * Add a team to the database
         */
        private void AddTeam(String tName, String tTag, UInt32 tCapt)
        {
            /** Declare database objects */
            DataSet ds = new DataSet();
            SqlDataAdapter da;
            DataRow newTeam;

            /** Build query string */
            String sQry = "SELECT * FROM compos_teams";

            try
            {
                /** Create DataAdapter¨*/
                da = new SqlDataAdapter(sQry, rwDb.getDbConn());

                ///** Set insert command */
                da.InsertCommand = new SqlCommand("lmCreateTeam", rwDb.getDbConn());
                da.InsertCommand.CommandType = CommandType.StoredProcedure;

                ///** Map SProc parameters */
                da.InsertCommand.Parameters.Add("@TeamName", SqlDbType.VarChar, 50, "naam");
                da.InsertCommand.Parameters.Add("@TeamTag", SqlDbType.VarChar, 5, "tag");
                da.InsertCommand.Parameters.Add("@CaptId", SqlDbType.Int, 0, "captain_id");

                /** Get the schema from the Teams table */
                da.FillSchema(ds, SchemaType.Source, "teams");

                /** Create and fill new row */
                newTeam = ds.Tables["teams"].NewRow();
                newTeam["naam"] = tName.Trim();
                newTeam["tag"] = tTag.Trim();
                newTeam["captain_id"] = tCapt;

                /** Push row to DataTable */
                ds.Tables["teams"].Rows.Add(newTeam);

                /** Push DataTable to database */
                da.Update(ds, "teams");
            }
            catch
            {
                throw;
            }
        }

        #endregion

        #region Event Handlers

        /**
         * Event: CreateTeam::txtTeamName~Leave
         */
        private void txtTeamName_Leave(object sender, EventArgs e)
        {

        }

        /**
         * Event: CreateTeam::txtTeamTag~Enter
         * Occurs when Tag field is focussed.
         */
        private void txtTeamTag_Enter(object sender, EventArgs e)
        {
            /** Clear the box if it has default value */
            if (txtTeamTag.Text == this.lmLang.GetString("cteam.txtTeamTag"))
                txtTeamTag.Clear();
            /** Darken the color */
            txtTeamTag.ForeColor = Color.Black;
        }

        /**
         * Event: CreateTeam::txtTeamTag~Leave
         * Occurs when Tag field loses focus.
         */
        private void txtTeamTag_Leave(object sender, EventArgs e)
        {
            if (txtTeamTag.Text.Length == 0)
            {
                /** Reset the default */
                txtTeamTag.Text = this.lmLang.GetString("cteam.txtTeamTag");
                /** Lighten up the color */
                txtTeamTag.ForeColor = Color.Gray;
            }
        }

        /**
         * Event: CreateTeam::InputCheck
         * Checks the input after every character.
         */
        private void InputCheck(object sender, EventArgs e)
        {
            bool btnState = false;

            /** No empty input */
            if (txtTeamName.Text.Length > 3)
            {
                /** Check if the entered team name isn't taken yet */
                if (TeamTaken(txtTeamName.Text, txtTeamTag.Text))
                {
                    /** Team already exists */
                    lblTeamNameErr.Text = this.lmLang.GetString("cteam.errTeam");
                    lblTeamNameErr.ForeColor = Color.Red;
                }
                else
                {
                    /** Team name available */
                    lblTeamNameErr.Text = this.lmLang.GetString("cteam.passTeam");
                    lblTeamNameErr.ForeColor = Color.Green;

                    /** Tag filled in ? */
                    if (txtTeamTag.Text != lmLang.GetString("cteam.txtTeamTag") && txtTeamTag.Text.Length > 0)
                    {
                        /** Check passes and tag is filled in */
                        btnState = true;
                    }
                }

                /** Make the control visible */
                lblTeamNameErr.Visible = true;
            }
            else
            {
                lblTeamNameErr.Visible = false;
            }

            /** Apply changes */
            btnCreateTeam.Enabled = btnState;
        }

        /**
         * Event: CreateTeam::btnCreateTeam~Click
         */
        private void btnCreateTeam_Click(object sender, EventArgs e)
        {
            try
            {
                AddTeam(txtTeamName.Text, txtTeamTag.Text, lmUser.ID);
                MessageBox.Show(lmLang.GetString("cteam.teamCreated"), lmLang.GetString("compos.btnCreateTeam"));
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
    }
}
